<template>
  <!-- 头部 -->
  <header class="header">
    <img src="../../assets/logo4.png" alt="Logo" class="logo" />
    <nav class="navbar">
      <!-- 用户信息下拉 -->
      <div class="user-dropdown" @mouseenter="showDropdown = true" @mouseleave="showDropdown = false">
        <span class="nav-link user-container">
          <el-icon>
            <User />
          </el-icon>
          <span>{{ currentUser.name || currentUser.username }}</span>个人中心
        </span>
        <div v-show="showDropdown" class="dropdown-menu">
          <router-link to="/student/user" class="dropdown-item">查看个人信息</router-link>
          <router-link to="/login" class="dropdown-item">退出登录</router-link>
        </div>
      </div>
      
    </nav>
    
  </header>

  <!-- 主内容区域（整个 flex 容器包含菜单和右侧内容） -->
  <div style="display: flex">
    <!-- 左侧菜单 -->
    <div class="sidebar-container">
      <el-menu router :default-active="$route.path" class="custom-menu" background-color="#f8f9fa" text-color="#495057"
        active-text-color="#2c3e50">
        <el-menu-item index="Home" class="menu-item">
          <template #title>
            <el-icon>
              <HomeFilled />
            </el-icon>
            <span>系统首页</span>
          </template>
        </el-menu-item>

        <el-menu-item index="/student/user" class="menu-item">
          <template #title>
            <el-icon>
              <User />
            </el-icon>
            <span>个人信息</span>
          </template>
        </el-menu-item>

        <el-menu-item index="Job" class="menu-item">
          <template #title>
            <el-icon>
              <Briefcase />
            </el-icon>
            <span>选择岗位</span>
          </template>
        </el-menu-item>

        <el-menu-item index="SpeechEvaluation" class="menu-item">
          <template #title>
            <el-icon>
              <ChatLineRound />
            </el-icon>
            <span>语音训练</span>
          </template>
        </el-menu-item>

        <el-menu-item index="QuestionTraining" class="menu-item">
          <template #title>
            <el-icon>
              <Document />
            </el-icon>
            <span>题目训练</span>
          </template>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 右侧内容（子路由在此渲染） -->
    <div class="content-area">
      <router-view></router-view>
    </div>
  </div>

  <!-- 打开 Chat 按钮 -->
  <el-button v-if="canButtonVisible.buttonVisible"
    @click="() => { canDrawerVisible.setDrawerVisible(true); canButtonVisible.setButtonVisible(false) }"
    class="chat-button">
    <img src="@/assets/image2.png" alt="Chat Icon" class="chat-icon">
    打开 Chat
  </el-button>

  <el-drawer v-model="canDrawerVisible.drawerVisible" :direction="'rtl'" :size="drawerWidth + 'px'" :show-close="true"
    :modal="false" custom-class="resizable-drawer" ref="drawerRef">
    <!-- 将拖拽条放在Chat组件外层 -->
    <div class="drawer-content-wrapper">
      <div class="resizer" @mousedown="startResizing"></div>
      <Chat />
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import axios from 'axios'
import router from '@/router/index'
import Chat from '@/components/ChatWithAI.vue'
import { getToken, parseJwt } from '@/utils/auth'
import { useDrawerVisibleStore } from '@/stores/canDrawerVisible'
import { useButtonVisibleStore } from '@/stores/canButtonVisible'
import {
  HomeFilled,
  Monitor,
  DataAnalysis,
  Document,
  Microphone,
  UserFilled,
  ChatLineRound,
  Briefcase,
  Connection,
  Avatar,
  DocumentChecked,
  Reading,
  User
} from '@element-plus/icons-vue'

// 状态管理
const canDrawerVisible = useDrawerVisibleStore()
const canButtonVisible = useButtonVisibleStore()

// 用户信息状态
const currentUser = ref({})
const showDropdown = ref(false)

// 抽屉相关状态
const drawerWidth = ref(600) // 初始宽度
const isResizing = ref(false)

// 监听抽屉可见性变化
watch(
  () => canDrawerVisible.drawerVisible,
  (newVal) => {
    if (!newVal) {
      canButtonVisible.buttonVisible = true
    }
  }
)

// 调整抽屉大小的函数
const startResizing = (e) => {
  isResizing.value = true
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', stopResizing)
}

const handleMouseMove = (e) => {
  if (!isResizing.value) return

  const newWidth = window.innerWidth - e.clientX
  const minWidth = 200
  const maxWidth = 800

  drawerWidth.value = Math.min(Math.max(newWidth, minWidth), maxWidth)
}

const stopResizing = () => {
  isResizing.value = false
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', stopResizing)
}

// 加载用户信息
const loadUserInfo = () => {
  const userInfoStr = localStorage.getItem('userInfo')
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr)
      currentUser.value = userInfo
    } catch (e) {
      console.error('解析用户信息失败', e)
    }
  } else {
    console.warn('⚠️ 无法获取用户信息')
    router.push('/login') // 如果没有 userInfo，直接跳回登录页
  }
}

// 登出方法
const logout = () => {
  // 清除 token 和用户信息
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')

  // 跳转到登录页
  router.push('/login')
}

// 加载学校名称
const loadSchoolName = () => {
  const token = getToken()
  if (!token) {
    console.warn('未登录')
    return
  }

  const userInfo = parseJwt(token)
  if (!userInfo || !userInfo.id) {
    console.warn('用户信息异常')
    return
  }

  // 检查是否已经有缓存数据
  const cachedData = JSON.parse(localStorage.getItem('cachedSchoolData'))
  if (cachedData) {
    updateCurrentUserWithSchoolName(cachedData.schoolName)
    return
  }

  // 如果没有缓存，则请求接口
  axios.get(`/api/school/info/${userInfo.id}`, {
    headers: {
      Authorization: 'Bearer ' + token
    }
  })
    .then(res => {
      if (res.data && res.data.code === 200 && res.data.data) {
        const schoolName = res.data.data.schoolName
        updateCurrentUserWithSchoolName(schoolName)

        // 可选：缓存学校数据
        localStorage.setItem('cachedSchoolData', JSON.stringify(res.data.data))
      }
    })
    .catch(err => {
      console.error('获取学校名称失败:', err)
    })
}

// 更新 currentUser 的方法
const updateCurrentUserWithSchoolName = (schoolName) => {
  const userInfoStr = localStorage.getItem('userInfo')
  if (!userInfoStr) {
    console.warn('⚠️ localStorage 中无 userInfo，无法更新 school_name')
    return
  }

  try {
    const userInfo = JSON.parse(userInfoStr)
    userInfo.school_name = schoolName
    localStorage.setItem('userInfo', JSON.stringify(userInfo))

    // 更新 Vue 组件中的 currentUser
    currentUser.value = userInfo
  } catch (e) {
    console.error('更新用户信息失败:', e)
  }
}

// 生命周期钩子
onMounted(() => {
  loadUserInfo()
  if (currentUser.value.role === 'school') {
    loadSchoolName()
  }
})
</script>

<style scoped>
/* 全局样式 */
.home-container {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 头部样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #2c3e50;
  color: white;
  height: 30px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  width: 30px;
  height: auto;
}

.navbar {
  display: flex;
  align-items: center;
  gap: 15px;
}

.nav-link {
  text-decoration: none;
  color: white;
  font-weight: bold;
  transition: color 0.3s ease;
  cursor: pointer;
}

/* 用户下拉菜单 */
.user-dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  min-width: 120px;
}

.dropdown-item {
  display: block;
  padding: 10px 15px;
  text-decoration: none;
  color: #333;
  transition: background-color 0.2s;
}

.dropdown-item:hover {
  background-color: #f0f0f0;
}

.user-container {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
}

.user-container .el-icon {
  font-size: 18px;
  color: white;
}

/* 侧边栏样式 */
.sidebar-container {
  width: 220px;
  border-right: 1px solid #e6e6e6;
  height: calc(100vh - 60px);
  background-color: #f8f9fa;
  transition: width 0.3s;
}

.custom-menu {
  border-right: none;
}

.menu-item {
  height: 48px;
  line-height: 48px;
  margin: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.menu-item:hover {
  background-color: #e9ecef;
}

.menu-item.is-active {
  background-color: #e9ecef;
  font-weight: 500;
  border-left: 3px solid #2c3e50;
}

.menu-item .el-icon {
  font-size: 18px;
  margin-right: 8px;
  color: #495057;
}

.menu-item span {
  font-size: 14px;
}

/* 内容区域 */
.content-area {
  flex: 1;
  width: 0;
  background-color: #e1e4eb;
  padding: 20px;
  overflow-y: auto;
  height: calc(100vh - 60px);
}

/* Chat按钮样式 */
.chat-button {
  position: fixed;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 9999;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
  background-color: white;
  color:  #2c3e50;
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.chat-button:hover {
  background-color:#f0f1f1;
}

.chat-icon {
  width: 24px;
  height: 24px;
  margin-bottom: 4px;
}

/* 抽屉样式 */
.resizable-drawer .resizer {
  position: absolute;
  left: 0;
  top: 0;
  width: 5px;
  height: 100%;
  cursor: ew-resize;
}

.resizable-drawer .resizer:hover {
  background-color: #409EFF;
}
/* 确保抽屉容器有正确布局 */
.el-drawer__container {
  position: relative;
  overflow: visible !important;
}

.resizable-drawer {
  position: relative;
}
/* 确保拖拽条可见且可交互 */
.resizer {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 10px;
  background-color: rgba(64, 158, 255, 0.0); /* 半透明蓝色 */
  cursor: ew-resize; /* 水平调整大小的光标 */
  z-index: 10000;
  transition: all 0.2s ease;
}

/* 鼠标悬停时更明显 */
.resizer:hover {
  background-color: rgba(64, 158, 255, 0);
  width: 12px; /* 悬停时稍微变宽 */
}

/* 确保抽屉内容区域建立定位上下文 */
.el-drawer__body {
  position: relative;
  height: 100%;
}
</style>